﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Configuration;

namespace OAclient.Filters
{
    /// <summary>
    /// 访问日志类
    /// </summary>
    //[AttributeUsage(AttributeTargets.Class |AttributeTargets.Method,Inherited=true,AllowMultiple=true)]
    public class LoggerFilter : FilterAttribute, IActionFilter, IResultFilter
    {
        //获取存放在配置文件中的访问日志存放路径
        string logPath = ConfigurationManager.AppSettings["ExpLogPath"].ToString() + "Log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
        static object _object = new object();

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="controller">controller名称</param>
        /// <param name="action">action名称</param>
        /// <param name="exMessage">访问信息</param>
        /// <param name="ip">客户端ip</param>
        void WriteLog(string controller, string action, string message, string ip)
        {
            string root_logpath = HttpContext.Current.Request.MapPath(ConfigurationManager.AppSettings["ExpLogPath"].ToString());
            if (!Directory.Exists(root_logpath))
                Directory.CreateDirectory(root_logpath);
            //获取站点相对路径
            string path = HttpContext.Current.Request.MapPath(logPath);
            lock (_object)
            {
                //通过文件流写入日志
                using (FileStream fs = new FileStream(path, FileMode.Append))
                {
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        //写入访问信息
                        writer.WriteLine("################# Begin #################");
                        writer.WriteLine("Time:[{0}]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        writer.WriteLine("Controller:{0}", controller);
                        writer.WriteLine("Action:{0}", action);
                        writer.WriteLine("Message:{0}", message);
                        writer.WriteLine("IPAddress:{0}", ip);

                        //writer.WriteLine("Operating System version is:{0}", System.Environment.OSVersion.Version.ToString());
                        //writer.WriteLine("Current Thread ID is:{0}", AppDomain.GetCurrentThreadId());

                        //此处为获取CLR的线程ID，非Windows线程，不可用
                        //Thread t = new Thread(new ThreadStart(WriteLog));
                        //writer.WriteLine("Current Thread ID is:{0}", t.ManagedThreadId);

                        writer.WriteLine("############### Over ###############");
                    }
                }
            }
        }

        /// <summary>
        /// 重写IActionFilter正在请求的方法
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //获取客户端ip
            string ip = (filterContext.HttpContext.Request.ServerVariables["HTTP_VIA"] != null) ? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            //调用写入日志的方法
            WriteLog(filterContext.RouteData.Values["controller"].ToString(),
                filterContext.RouteData.Values["action"].ToString(),
                "开始请求Action", ip);
        }

        /// <summary>
        /// 重写IActionFilter请求结束的方法
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //获取客户端ip
            string ip = (filterContext.HttpContext.Request.ServerVariables["HTTP_VIA"] != null) ? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            //调用写入日志的方法
            WriteLog(filterContext.RouteData.Values["controller"].ToString(),
                filterContext.RouteData.Values["action"].ToString(),
                "Action请求完成", ip);
        }

        /// <summary>
        /// 重写IResultFilter正在执行返回结果的方法
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            //获取客户端ip
            string ip = (filterContext.HttpContext.Request.ServerVariables["HTTP_VIA"] != null) ? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            //调用写入日志的方法
            WriteLog(filterContext.RouteData.Values["controller"].ToString(),
                filterContext.RouteData.Values["action"].ToString(),
                "开始返回Result", ip);
        }

        /// <summary>
        /// 重写IResultFilter返回结果结束的方法
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            //获取客户端ip
            string ip = (filterContext.HttpContext.Request.ServerVariables["HTTP_VIA"] != null) ? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            //调用写入日志的方法
            WriteLog(filterContext.RouteData.Values["controller"].ToString(),
                  filterContext.RouteData.Values["action"].ToString(),
                  "返回Result结束", ip);
        }

    }
}
